﻿using System.Linq;
using System.Xml;
using DataScripter.Containers;
using DataScripter.Database;
using DataScripter.Scripting;
using DataScripter.Scripting.InputSources;

namespace DataScripter.XmlInterpreter.XmlInterpreters
{
    public class InputSourceInterpreter : IXmlInterpreter<IInputSource>
    {
        private IContainer Container { get; set; }

        public InputSourceInterpreter(IContainer container)
        {
            Container = container;
        }

        public IInputSource InterpretElement(XmlElement element)
        {
            string name = element.GetAttribute("Name");
            string type = element.GetAttribute("Type");

            IInputSource source = null;
            // TODO: replace with proper factory or IOC magic
            if (type == "SqlServer")
            {
                source = new SqlServerInputSource(name, Container);
                Container.RegisterType((ISqlServerInputSource) source);
                InterpretSqlServerInputSource(element, (ISqlServerInputSource)source);
            }
            return source;
        }

        private static void InterpretSqlServerInputSource(XmlElement element, ISqlServerInputSource source)
        {
            foreach (XmlElement child in element.ChildNodes.OfType<XmlElement>())
            {
                switch (child.Name)
                {
                    case "ConnectionString":
                        string connectionString = child.InnerText;
                        source.ConnectionString = connectionString;
                        break;
                    case "DataProducer":
                        source.Register<IDataProducer>(child);
                        break;
                    case "Db":
                        source.Register<Db>(child);
                        break;
                    case "DatabaseStructure":
                        source.Register<IDatabaseStructure>(child);
                        break;
                }
            }
        }
    }
}
